package com.aco.fatureapp.activity;

import roboguice.inject.ContentView;
import roboguice.inject.InjectView;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.aco.fatureapp.R;
import com.aco.fatureapp.model.TypeReturnFind;

@ContentView(R.layout.activity_search_metering)
public class SearchMeteringActivity extends BaseActivity {

	@InjectView(R.id.txtInscricao)
	private EditText mTxtInscricao;

	@InjectView(R.id.txtHidrometro)
	private EditText mTxtHidrometro;

	@InjectView(R.id.txtPosicao)
	private EditText mTxtPosicao;

	@InjectView(R.id.btnSearch)
	private Button mBtnSearch;

	@InjectView(R.id.btnCancel)
	private Button mBtnCancel;

	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setFinishOnTouchOutside(false);

		/**
		 * Registrando Eventos
		 */
		mBtnSearch.setOnClickListener(preencherFiltroPesquisa());

		mBtnCancel.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(final View v) {
				finish();
			}
		});
	}

	private OnClickListener preencherFiltroPesquisa() {
		return new OnClickListener() {

			@Override
			public void onClick(final View v) {

				if ((mTxtInscricao.getText().toString().length() > 0)
						|| (mTxtHidrometro.getText().toString().length() > 0)
						|| (mTxtPosicao.getText().toString().length() > 0))

				{
					TypeReturnFind typeReturnFind = mTxtPosicao.getText()
							.toString().length() > 0 ? new TypeReturnFind(
							TypeFilter.FILTRO_POSICAO.ordinal(), mTxtPosicao
									.getText().toString()) : null;

					if (typeReturnFind == null) {
						typeReturnFind = mTxtInscricao.getText().toString()
								.length() > 0 ? new TypeReturnFind(
								TypeFilter.FILTRO_INSCRICAO.ordinal(),
								mTxtInscricao.getText().toString()) : null;
					}

					if (typeReturnFind == null) {
						typeReturnFind = mTxtHidrometro.getText().toString()
								.length() > 0 ? new TypeReturnFind(
								TypeFilter.FILTRO_HIDROMETRO.ordinal(),
								mTxtHidrometro.getText().toString()) : null;
					}

					setResult(
							RESULT_OK,
							getIntent().putExtra(TypeReturnFind.SEARCH_VALUE,
									typeReturnFind));
					finish();
				}
				else {
					Toast.makeText(SearchMeteringActivity.this,
							"Preencha um dos filtros para pesquisar!",
							Toast.LENGTH_LONG).show();
				}
			}
		};
	}

	public enum TypeFilter {
		FILTRO_HIDROMETRO, FILTRO_INSCRICAO, FILTRO_POSICAO;

		public static TypeFilter valueOf(Integer ordinal) {
			TypeFilter[] values = TypeFilter.values();
			for (TypeFilter typeFilter : values) {
				if (typeFilter.ordinal() == ordinal) {
					return typeFilter;
				}
			}

			return null;
		}
	}

}
